import React, { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import Header from './Header';
import './Upload.css';

const Upload = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isDragging, setIsDragging] = useState(false);
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef(null);

  // Check for mock authentication
  const isAuthenticated = !!localStorage.getItem('mockAuthToken');
  const user = isAuthenticated ? JSON.parse(localStorage.getItem('mockUser') || '{}') : null;

  const handleDragEnter = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  };

  const handleDragLeave = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  };

  const handleDragOver = (e) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
    
    const files = Array.from(e.dataTransfer.files);
    handleFiles(files);
  };

  const handleFileInput = (e) => {
    const files = Array.from(e.target.files);
    handleFiles(files);
  };

  const handleFiles = (files) => {
    const validFiles = files.filter(file => 
      file.type.startsWith('image/') || 
      file.type.startsWith('video/')
    );
    
    if (validFiles.length === 0) {
      alert(t('upload.invalidFileType'));
      return;
    }
    
    const newFiles = validFiles.map(file => ({
      id: Date.now() + Math.random(),
      file,
      name: file.name,
      size: (file.size / 1024 / 1024).toFixed(2) + ' MB',
      type: file.type.startsWith('image/') ? 'image' : 'video',
      preview: file.type.startsWith('image/') ? URL.createObjectURL(file) : null,
      status: 'pending'
    }));
    
    setUploadedFiles(prev => [...prev, ...newFiles]);
  };

  const removeFile = (id) => {
    setUploadedFiles(prev => prev.filter(file => file.id !== id));
  };

  const uploadFiles = () => {
    if (uploadedFiles.length === 0) {
      alert(t('upload.noFiles'));
      return;
    }
    
    setIsUploading(true);
    
    // Simulate upload process
    setTimeout(() => {
      setUploadedFiles(prev => 
        prev.map(file => ({ ...file, status: 'completed' }))
      );
      setIsUploading(false);
      alert(t('upload.uploadSuccess'));
      
      // Navigate to timeline after successful upload
      setTimeout(() => {
        navigate('/timeline');
      }, 1500);
    }, 2000);
  };

  const openFileDialog = () => {
    fileInputRef.current.click();
  };

  if (!isAuthenticated) {
    navigate('/auth');
    return null;
  }

  return (
    <div className="upload-container">
      <Header />
      <div className="upload-content">
        <div className="upload-header">
          <h1 className="upload-title">{t('upload.title')}</h1>
          <p className="upload-subtitle">{t('upload.subtitle')}</p>
        </div>

        <div className="upload-area">
          <div 
            className={`drop-zone ${isDragging ? 'dragging' : ''}`}
            onDragEnter={handleDragEnter}
            onDragLeave={handleDragLeave}
            onDragOver={handleDragOver}
            onDrop={handleDrop}
            onClick={openFileDialog}
          >
            <div className="drop-zone-content">
              <div className="upload-icon">📤</div>
              <h3>{t('upload.dragDropTitle')}</h3>
              <p>{t('upload.dragDropText')}</p>
              <button className="browse-btn">
                {t('upload.browseFiles')}
              </button>
              <p className="file-types">{t('upload.supportedFormats')}</p>
            </div>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept="image/*,video/*"
              onChange={handleFileInput}
              style={{ display: 'none' }}
            />
          </div>
        </div>

        {uploadedFiles.length > 0 && (
          <div className="upload-list">
            <h3>{t('upload.filesToUpload')} ({uploadedFiles.length})</h3>
            <div className="file-list">
              {uploadedFiles.map(file => (
                <div key={file.id} className="file-item">
                  {file.preview ? (
                    <img src={file.preview} alt={file.name} className="file-preview" />
                  ) : (
                    <div className="file-icon">
                      {file.type === 'video' ? '🎬' : '🖼️'}
                    </div>
                  )}
                  <div className="file-info">
                    <h4 className="file-name">{file.name}</h4>
                    <p className="file-size">{file.size}</p>
                    <div className="file-status">
                      {file.status === 'pending' && (
                        <span className="status-pending">{t('upload.pending')}</span>
                      )}
                      {file.status === 'uploading' && (
                        <span className="status-uploading">{t('upload.uploading')}</span>
                      )}
                      {file.status === 'completed' && (
                        <span className="status-completed">{t('upload.completed')}</span>
                      )}
                    </div>
                  </div>
                  <button 
                    className="remove-btn"
                    onClick={() => removeFile(file.id)}
                    disabled={isUploading}
                  >
                    ✕
                  </button>
                </div>
              ))}
            </div>
            
            <div className="upload-actions">
              <button 
                className="cancel-btn"
                onClick={() => setUploadedFiles([])}
                disabled={isUploading}
              >
                {t('upload.cancel')}
              </button>
              <button 
                className="upload-btn"
                onClick={uploadFiles}
                disabled={isUploading || uploadedFiles.length === 0}
              >
                {isUploading ? (
                  <>
                    <div className="spinner"></div>
                    {t('upload.uploading')}
                  </>
                ) : (
                  t('upload.upload')
                )}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Upload;